import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { postApi } from '@/api/public/post'
import type { Post, PostComment } from '@/types/post'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export const useGuideDetail = () => {
  const route = useRoute()
  const post = ref<Post | null>(null)
  const comments = ref<PostComment[]>([])

  const fetchPostDetail = async () => {
    try {
      const id = Number(route.params.id)
      const response = await postApi.getDetail(id)
      if (response.data.code === 200) {
        post.value = response.data.data
      }
    } catch (error) {
      console.error('获取文章详情失败:', error)
      ElMessage.error('获取文章详情失败')
    }
  }

  const fetchComments = async () => {
    try {
      const id = Number(route.params.id)
      const response = await postApi.getComments(id)
      if (response.data.code === 200) {
        comments.value = response.data.data
      }
    } catch (error) {
      console.error('获取评论失败:', error)
      ElMessage.error('获取评论失败')
    }
  }

  const formatDate = (date: string) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm')
  }

  onMounted(() => {
    fetchPostDetail()
    fetchComments()
  })

  return {
    post,
    comments,
    formatDate,
    fetchComments
  }
} 